/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.ConversionException;
import org.digitalsoul.switchplugin.matchers.Matcher;
import org.digitalsoul.switchplugin.model.Configuration;
import org.digitalsoul.switchplugin.model.SwitchItem;
import org.digitalsoul.switchplugin.model.SwitchSet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class XMLConverter {

    private XMLConverter(){
    }
    
    public static SwitchSet importSet(File file) {
        SwitchSet set = null;
        try {
            XStream xstream = getXStream();
            set = (SwitchSet) xstream.fromXML(new FileInputStream(file));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return set;
    }

    private static XStream getXStream() {
        XStream xstream = new XStream();
        xstream.alias("Set", SwitchSet.class);
        xstream.alias("Item", SwitchItem.class);
        xstream.omitField(Matcher.class, "matches");
        return xstream;
    }
    
    public static void exportSet(SwitchSet set, String path) {
        try {
            getXStream().toXML(set, new FileOutputStream(new File(path)));
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static String configToXML(Configuration config) {
        return getXStream().toXML(config);
    }
    
    private static Object loadFromXML(String xml) throws ConversionException {
        return getXStream().fromXML(xml);
    }
    
    public static Configuration xmlToConfig (String xml)  {
        return (Configuration) loadFromXML(xml);
    }
}
